package cn.source.system.service.impl;

import cn.source.common.annotation.DataSource;
import cn.source.common.core.redis.RedisCache;
import cn.source.common.enums.DataSourceType;
import cn.source.common.enums.GongzhonghaoContent;
import cn.source.common.utils.DateUtils;
import cn.source.common.utils.StringUtils;
import cn.source.system.controller.CmsWxApiController;
import cn.source.system.domain.CmsAliKey;
import cn.source.system.domain.SendMessage;
import cn.source.system.mapper.CmsAliKeyMapper;
import cn.source.system.service.WxApiService;
import cn.source.system.utils.WxUtil;
import cn.source.system.websocket.WebSocketUsers;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Service
public class WxApiServiceImpl implements WxApiService {
    private static final Logger logger = LoggerFactory.getLogger(CmsWxApiController.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CaptchaServiceImpl captchaService;

    @Autowired
    private CmsAliKeyMapper cmsAliKeyMapper;

    @Value("${wechat.mp.appId}")
    private String APPID;

    @Value("${wechat.mp.secret}")
    private String SECRET;

    @Value("${wechat.mp.accessTokenKey}")
    private String accessTokenKey;

    private String aliKeyPrefix = "https://www.aliyundrive.com/s/";

    @Override
    public String subscribeProcessor(HttpServletRequest request) throws Exception {
        // 通过IO获得Document
        SAXReader reader = new SAXReader();
        Document doc = reader.read(request.getInputStream());
        // 得到xml的根节点
        Element root = doc.getRootElement();
        String toUserName = root.elementText("ToUserName");//开发者微信号
        String fromUserName = root.elementText("FromUserName");//发送方帐号（一个OpenID）
        String createTime = root.elementText("CreateTime");//消息创建时间 （整型）
        String msgType = root.elementText("MsgType");//消息类型，event
        String event = root.elementText("Event");//事件类型，subscribe(订阅)、unsubscribe(取消订阅),SCAN
        String eventKey = root.elementText("EventKey");// 事件KEY值，qrscene_为前缀，后面为二维码的参数值
        String ticket = root.elementText("Ticket"); // 二维码的ticket，可用来换取二维码图片
        String content = root.elementText("Content");
        String msgId = root.elementText("MsgId");
        logger.info("微信公众号接收信息:{},{},{},{},{},{},{},{}", toUserName, fromUserName, createTime, msgType, event, eventKey, ticket, content);

        // 定义变量判断是否已关注，已经关注则自动登录，否则等待subscribe关注事件
        if (StringUtils.isNotEmpty(ticket)) {
            Object token = redisCache.getCacheObject(accessTokenKey);
            Map map = WxUtil.obtainUserDetail(token.toString(), fromUserName);
            String ticketCacheKey = DateUtils.getDate() + ":" + ticket;
            String sessionId = redisCache.getCacheObject(ticketCacheKey);
            // sessionId可能已经失效，则不发消息
            if (StringUtils.isNotNull(sessionId)) {
                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.get(sessionId), map.get("subscribe").toString());
            }
        }

        if (StringUtils.isNotEmpty(content)) {
            String returnContent = "暂时未找到信息，请换个关键词试试吧";

            if (content.equals("验证码")) {
                returnContent = captchaService.getCode(toUserName);
            } else {
                returnContent = GongzhonghaoContent.fromString(content).getValue();
            }

            if (GongzhonghaoContent.NONE.getValue().equalsIgnoreCase(returnContent)) {
                CmsAliKey cmsAliKey = new CmsAliKey();

                cmsAliKey.setTitle(content);

                List<CmsAliKey> cmsAliKeys = cmsAliKeyMapper.selectCmsAliKeyList(cmsAliKey);

                if (cmsAliKeys.size() > 0) {
                    StringBuilder newContent = new StringBuilder("");
                    for (CmsAliKey aliKey : cmsAliKeys) {
                        newContent.append(aliKey.getTitle()).append(":").append(aliKeyPrefix + aliKey.getAlikey()).append("\n");
                    }
                    returnContent = String.valueOf(newContent);
                }
            }

            SendMessage sendMessage = new SendMessage();

            sendMessage.setContent(returnContent);
            sendMessage.setCreateTime(createTime);
            sendMessage.setFromUserName(toUserName);
            sendMessage.setToUserName(fromUserName);
            sendMessage.setMsgType("text");

            logger.info("微信公众号返回信息:{}", sendMessage.toString());
            return sendMessage.toString();
        }

        return "success";
    }
}
